package MCQReaderInterface;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

import MCQReaderAnsweredAnalyze.AnsewredQCMAnalyse;
import MCQReaderModel.ModelManager;

public class MCQReaderMenu extends JMenuBar implements ActionListener {

	/***************************************
	 * Class Variables*
	 ***************************************/
	private static final long serialVersionUID = 1L;
	private MainInterface myOwner;
	private JMenu file;
	private File filePDF = null;
	private JMenuItem open, get, save, export, exit, analyse;
	private JMenu help;
	private JMenuItem helpC, about;

	/***************************************
	 * Constructor *
	 ***************************************/
	MCQReaderMenu(MainInterface mi) {
		super();
		myOwner = mi;

		/* %%%%%%%%%%%%%%%%%%%%%%% Menus Creation %%%%%%%%%%%%%%%%%%%%%%% */
		file = new JMenu("File");
		help = new JMenu("Help");

		/* %%%%%%%%%%%%%%%%%%%%%%% Menu abbrevations:Alt+..%%%%%%%%%%%%%%% */

		file.setMnemonic('F');
		help.setMnemonic('H');

		/* %%%%%%%%%%%%%%%%%%%%%% Menu elements creation %%%%%%%%%%%%%%%%% */

		open = new JMenuItem("Open PDF");
		get = new JMenuItem("Import Model");
		save = new JMenuItem("Save Model");
		export = new JMenuItem("Export");
		analyse = new JMenuItem("Analyse");
		exit = new JMenuItem("Exit");

		helpC = new JMenuItem("Buttons control");
		about = new JMenuItem("About QCMLayer");

		/* %%%%%%%%%%%%%%%%%%%%% adding Action to menu element %%%%%%%%%%%% */

		open.addActionListener(this);
		analyse.addActionListener(this);
		get.addActionListener(this);
		save.addActionListener(this);
		export.addActionListener(this);
		exit.addActionListener(this);
		helpC.addActionListener(this);
		about.addActionListener(this);

		/* %%%Adding abbreviation to all menu elements to facilitate its uses%% */

		// open:ctrl+o
		open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
				KeyEvent.CTRL_MASK));
		// get:ctrl+g
		get.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G,
				KeyEvent.CTRL_MASK));
		// save:ctrl+s
		save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
				KeyEvent.CTRL_MASK));

		// export.setEnabled(false);
		// export.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
		// KeyEvent.CTRL_DOWN_MASK + KeyEvent.SHIFT_DOWN_MASK));

		// analyse:crtl+a
		analyse.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
				KeyEvent.CTRL_MASK));

		// exit:ctrl+q
		exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
				KeyEvent.CTRL_MASK));

		// helpc:ctrl+h
		helpC.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
				KeyEvent.CTRL_MASK));

		// about:ctrl+p
		about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
				KeyEvent.CTRL_MASK));

		/* %%%%%%%%%%%%% Adding menu elements to the right submenu%%%%%%%%%% */

		file.add(open);
		file.add(get);
		file.add(save);
		// file.add(export);
		file.add(analyse);
		file.add(exit);

		help.add(helpC);
		help.add(about);

		this.add(file);
		this.add(help);
	}

	/***************************************
	 * Class Methods*
	 ***************************************/
	/*
	 * creates a new File Chooser enabling the user to choose a file having a
	 * determined extension to open
	 * 
	 * @param description the file description extentsion the file extension
	 * title the title of the dialog window
	 * 
	 * @return fc the created File chooser
	 */
	private JFileChooser createFileChooser(String description,
			String extension, String title) {
		// Create a file chooser
		JFileChooser fc = new JFileChooser();
		// open files which have just this extension
		fc.setAcceptAllFileFilterUsed(false);
		fc.addChoosableFileFilter(new FileNameExtensionFilter(description,
				extension));
		// change the title of the dialog window
		fc.setDialogTitle(title);
		return fc;
	}

	/*
	 * open a pdf file in the left frame of the interface in response to a
	 * button click(open)
	 * 
	 * @param fc the file chooser enabling the user to choose files tu open m
	 * the menu button to click on f the file to open mi the interface in which
	 * the opened file will be shown
	 */
	private boolean openPdfFile(JFileChooser fc) {
		// in response to a button click
		int returnVal = fc.showOpenDialog(open);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			// getting the selected file
			filePDF = fc.getSelectedFile();
			// openning the selected file in the right Frame
			myOwner.getRightFrame().OpenPDF(filePDF.getAbsolutePath());
			myOwner.repaint();
			return true;
		}
		return false;
	}

	/*
	 * open a Model file in the right frame of the interface in response to a
	 * button click(open)
	 * 
	 * @param fc the file chooser enabling the user to choose files tu open m
	 * the menu button to click on
	 */
	private boolean openModelFile(JFileChooser fc) {
		int returnVal = fc.showOpenDialog(open);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			ModelManager.load(
					fc.getSelectedFile().getAbsolutePath());
			MCQReaderTree.parcourirNoeud(MainInterface.thisIsIt.getLeftFrame()
					.getTree().getRacine());
			return true;
		}
		return false;
	}

	/*
	 * reset extension of choosable file filtre in a File Chooser
	 * 
	 * @param fc The File Chooser description the file description extentsion
	 * the file extension title the title of the dialog window
	 */
	private void resetChoosableFileFiltre(JFileChooser fc, String description,
			String extension, String title) {
		if (fc != null) {
			fc.setAcceptAllFileFilterUsed(false);
			fc.resetChoosableFileFilters();
			fc.addChoosableFileFilter(new FileNameExtensionFilter(description,
					extension));
			fc.setDialogTitle(title);
		}
	}

	/*
	 * save the model file in response to a button click (save)
	 * 
	 * @param fc the file chooser m the menu button to click on
	 */
	private boolean saveModelFile(JFileChooser fc) {
		int returnVal = fc.showSaveDialog(save);

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			ModelManager.save(
					fc.getSelectedFile().getAbsolutePath() + ".xml");
			return true;
		}
		return false;

	}

	private boolean generateResultFile(JFileChooser fc) {
		// show just the extensions of ".csv"
		resetChoosableFileFiltre(fc, ".csv", "csv",
				"Choose a name for your result File !");

		// In response to a button click:
		int returnVal = fc.showSaveDialog(open);

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			AnsewredQCMAnalyse.startAnalyse(fc.getSelectedFile()
					.getAbsolutePath());
			return true;
		}
		return false;
	}

	@Override
	/* * * * * * *
	 * define the actions of the listners adding to the submenus * *
	 * 
	 * @param ea the action event * * * * * *
	 */
	public void actionPerformed(ActionEvent ea) {
		JFileChooser fc = new JFileChooser();

		if (ea.getSource() == open) {
			fc = createFileChooser(".pdf", "pdf", "open");
			openPdfFile(fc);

		} else if (ea.getSource() == get) {

			int reponse = JOptionPane.showConfirmDialog(null,
					"load your QCM",
					"Your QCM is already opened!", JOptionPane.YES_NO_OPTION);

			if (reponse == JOptionPane.YES_OPTION) {

				// open the QCM File
				resetChoosableFileFiltre(fc, ".pdf", "pdf",
						"Open the corresponding QCM");
				fc = createFileChooser(".pdf", "pdf",
						"Open the corresponding QCM");
			}
			if (reponse == JOptionPane.NO_OPTION || openPdfFile(fc)) {
				// Open the Model File to continue to work in
				resetChoosableFileFiltre(fc, ".xml", "xml",
						"load correspending Model File");
				openModelFile(fc);
			}

		}

		else if (ea.getSource() == analyse) {
			// If you are working on the model file
			// and you want to start the QCM answered analyze
			if (filePDF != null) {
				String[] choix = { "yes", "no", "cancel" };
				int reponse = JOptionPane
						.showOptionDialog(
								this,
								"If the current model file will be used in the analyse, save it before continuing \n Do you want to save this model file?",
								"Model File not saved !",
								JOptionPane.YES_NO_CANCEL_OPTION,
								JOptionPane.QUESTION_MESSAGE, null, choix,
								choix[2]);

				// if you choose to save the current model file before starting
				// the analyze

				if (reponse != JOptionPane.CANCEL_OPTION) {
					if (reponse == JOptionPane.YES_OPTION) {
						/*
						 * save the model file
						 */
						fc = createFileChooser(".xml", "xml", "Save Model File");
						if (saveModelFile(fc)) {

							/*
							 * begin the analysis of the answered QCM
							 */
							// Load the QCM
							resetChoosableFileFiltre(fc, ".pdf", "pdf",
									"Load the QCM you want to analyse");
							if (openPdfFile(fc)) {
								// load the model file
								resetChoosableFileFiltre(fc, ".xml", "xml",
										"Load the model File to analyse your QCM");
								if (openModelFile(fc)) {
									// lancer l'analyse et gerer fichier
									// résultat
									generateResultFile(fc);

								}
							}
						}
					}

					if (reponse == JOptionPane.NO_OPTION) {
						/*
						 * begin the analysis of the answered QCM
						 */
						// Load the QCM
						resetChoosableFileFiltre(fc, ".pdf", "pdf",
								"Load the QCM you want to analyse");
						if (openPdfFile(fc)) {
							// load the model file
							resetChoosableFileFiltre(fc, ".xml", "xml",
									"Load the model File to analyse your QCM");

							if (openModelFile(fc)) {
								// lancer l'analyse et gerer fichier
								// résultat
								generateResultFile(fc);
							}
						}
					}

				}
			} else {
				/*
				 * begin the analysis of the answered QCM
				 */
				// Load the QCM
				resetChoosableFileFiltre(fc, ".pdf", "pdf",
						"Load the QCM you want to analyse");
				if (openPdfFile(fc)) {
					// load the model file
					resetChoosableFileFiltre(fc, ".xml", "xml",
							"Load the model File to analyse your QCM");
					if (openModelFile(fc)) {
						// lancer l'analyse et gerer fichier résultat
						generateResultFile(fc);
					}

				}
			}
		}

		else if (ea.getSource() == save) {
			// Create a file chooser
			if (filePDF != null) {
				fc = createFileChooser(".xml", "xml", "save the model file");
				saveModelFile(fc);
			} else {
				JOptionPane.showMessageDialog(null,
						"No model file was generated ", "Information",
						JOptionPane.INFORMATION_MESSAGE, null);
			}

		}

		else if (ea.getSource() == exit) {
			// admin.exitFunction();
			Object[] options = { "Exit", "Cancel" };
			int i = JOptionPane.showOptionDialog(myOwner.getParent(),
					"Are you sure to Exit the program?\n", "...",
					JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
					null, options, options[0]);

			switch (i) {
			case JOptionPane.OK_OPTION:
				System.exit(0);
				break;
			case JOptionPane.CANCEL_OPTION:
				;
			}

		}

		else if (ea.getSource() == helpC) {
			JOptionPane.showMessageDialog(null, "How interface works? :\n"
					+ "Ctrl-q = exit the programm\n"
					+ "Ctrl-s = save the current file\n"
					+ "Ctrl-o = import a pdf file\n"
					+ "Ctrl-g = import a model file\n" + "Ctrl-h = ask help\n"
					+ "ctrl-p = Read me file" + "\n\n Utilities control:\n"
					+ "Ctrl-A = analyze the answered QCM\n" + "........\n"
					+ ".........\n", "Buttons control",
					JOptionPane.INFORMATION_MESSAGE);

		} else if (ea.getSource() == about) {
			JOptionPane.showMessageDialog(null, "Automatic QCM Analyser created by : HICHRI Houda, ROUASSI Amina, SAMBALA Paule, ZENATI Omar, KANE Ilyass, DIONE Pape, LISSY BARRO Maxime \n\n"
					+ ".................\n\n", "Read Me",
					JOptionPane.INFORMATION_MESSAGE);
		}
	}

}
